package org.langcom.io;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;

public class CustomObjectInputStream extends ObjectInputStream {

	private final ClassLoader classLoader;

	public CustomObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException {
		super(in);
		this.classLoader = classLoader;
	}

	@Override
	protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
		try {
			return Class.forName(desc.getName(), false, classLoader);
		} catch (ClassNotFoundException ex) {
			System.out.println("unable to resolve class : " + desc.getName());
			return super.resolveClass(desc);
		}
	}

	protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException {
		ClassLoader nonPublicLoader = null;
		boolean hasNonPublicInterface = false;

		// define proxy in class loader of non-public interface(s), if any
		Class[] classObjs = new Class[interfaces.length];
		for (int i = 0; i < interfaces.length; i++) {
			Class cl = Class.forName(interfaces[i], false, classLoader);
			if ((cl.getModifiers() & Modifier.PUBLIC) == 0) {
				if (hasNonPublicInterface) {
					if (nonPublicLoader != cl.getClassLoader()) {
						throw new IllegalAccessError(
							"conflicting non-public interface class loaders");
					}
				} else {
					nonPublicLoader = cl.getClassLoader();
					hasNonPublicInterface = true;
				}
			}
			classObjs[i] = cl;
		}
		try {
			return Proxy.getProxyClass(
				hasNonPublicInterface ? nonPublicLoader : classLoader,
				classObjs);
		} catch (IllegalArgumentException e) {
			throw new ClassNotFoundException(null, e);
		}
	}

}
